package com.hushui.mall.ware.service.impl;

import com.hushui.mall.ware.entity.PurchaseDetailEntity;
import com.hushui.mall.ware.entity.WareConstant;
import com.hushui.mall.ware.service.PurchaseDetailService;
import com.hushui.mall.ware.service.WareSkuService;
import com.hushui.mall.ware.vo.MergeVo;
import com.hushui.mall.ware.vo.PurChaseDetailDoneVo;
import com.hushui.mall.ware.vo.PurchaseDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hushui.common.utils.PageUtils;
import com.hushui.common.utils.Query;

import com.hushui.mall.ware.dao.PurchaseDao;
import com.hushui.mall.ware.entity.PurchaseEntity;
import com.hushui.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询新增的、已分配的采购单
     * @param params
     * @return
     */
    @Override
    public PageUtils queryUnreceivePurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",1).or().eq("status",0);

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 合并采购单
     * @param mergeVo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();

        //没有选择采购单就新建一个采购单
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            //设置采购单的默认属性，状态为新建
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());

            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);

            //获取新建采购单的id
            purchaseId = purchaseEntity.getId();
        }
        List<Long> items = mergeVo.getItems();

        //如果采购单是购买中的状态，就不能合并了

        //根据采购单id查询采购单需求
        Collection<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listByIds(items);

        //如果需求list里有某条采购单的状态不是新建或者已分配，就不能合并
        purchaseDetailEntities.forEach((item) -> {
            if (!item.getStatus().equals(WareConstant.PurchaseDetailStatusEnum.CREATED.getCode())
                    && !item.getStatus().equals(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode())) {
                throw new IllegalArgumentException("采购中，无法合并");
            }
        });

        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            //有采购单的情况下合并时，状态改成已分配
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        //批量修改
        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    /**
     * 采购员接取采购单
     * @param ids
     */
    @Transactional
    @Override
    public void received(List<Long> ids) {
        //查询当前采购单的状态是否为新建或者已分配
        List<PurchaseEntity> collect = ids.stream().map(i -> {
            PurchaseEntity byId = this.getById(i);
            return byId;
        }).filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || item.getStatus() ==
                    WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item -> {
            //过滤后，已接单的采购单状态更改为已接单
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            //更新采购单时间
            item.setCreateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        //完成修改
        this.updateBatchById(collect);

        //修改采购详情
        collect.forEach(item -> {
            //查询当前采购单的采购详情
            List<PurchaseDetailEntity> purchaseDetailEntityList =
                    purchaseDetailService.purchaseDetailListById(item.getId());
            //查到的采购单详情更改状态为 去采购
            List<PurchaseDetailEntity> detailLists = purchaseDetailEntityList.stream().map(p -> {
                PurchaseDetailEntity purchaseDetail = new PurchaseDetailEntity();
                purchaseDetail.setId(p.getId());
                purchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetail;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailLists);
        });


    }

    /**采购完成
     * {
     *    id: 123,//采购单id
     *    items: [{itemId:1,status:4,reason:""}]//完成/失败的采购单需求详情
     * }
     * @param purchaseDoneVo
     */
    @Transactional
    @Override
    public void end(PurchaseDoneVo purchaseDoneVo) {
        //完成采购逻辑
        //1.采购单里的每一条采购详情要更改状态
        //获取前端传来的采购单id，就在Vo里
        Long id = purchaseDoneVo.getId();
        //采购单的状态根据采购详情走，如果有一条采购详情没有完成，那么采购单的状态就是有异常，只有都完成的情况下，采购单才能已完成
        //2.采购单里的每一条采购详情也要更改状态
        //定义一个整体的采购单成功或失败标志
        Boolean st = true;
        //定义一个集合用来存放需要更新状态的采购详情
        List<PurchaseDetailEntity> newDetails = new ArrayList<>();
        //先得到所有的采购详情,详情就在Vo里，遍历
        List<PurChaseDetailDoneVo> items = purchaseDoneVo.getItems();
        for (PurChaseDetailDoneVo item : items) {
            //定义一个采购单对象
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            //如果其中一条采购详情是采购失败状态，那么整体标志就是失败，更改标志为假
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                st = false;
                //把这个采购详情状态放入对象中
                detailEntity.setStatus(item.getStatus());
            } else {
                //3.如果采购成功，把成功采购的商品入库（增加库存数量）
                //先改变这条采购详情的状态为已完成
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //先根据采购详情id查出商品
                PurchaseDetailEntity byId = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(byId.getSkuId(),byId.getWareId(),byId.getSkuNum());
            }
            //获取这个要更新的采购单详情ID
            detailEntity.setId(item.getItemId());
            //把所有要更新的采购单详情放入要更新的集合中
            newDetails.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(newDetails);

        //2.更改采购单的状态
        //判断采购单
        PurchaseEntity purchase = new PurchaseEntity();
        purchase.setId(id);

        purchase.setStatus(st?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchase.setUpdateTime(new Date());
        //更新采购单状态
        this.updateById(purchase);
    }

}
